package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 异常处理器  Global全局
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //自定义业务异常
    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException ex) {
        return R.error(ex.getMessage());
    }

    //违反唯一约束异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlException(SQLIntegrityConstraintViolationException ex) {
        //返回具体信息让用户体验好点
        //  失败原因:   sql唯一约束重复时一定会提示 Duplicate entry
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = split[2];
            msg = msg.replace("'", "");
            log.error("{} 已存在", msg);
            return R.error(msg + "已存在");
        }
        log.error(ex.getMessage());
        return R.error("未知错误");
    }


}
